/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.xml;

import com.google.common.base.Preconditions;
import com.google.dspl.jaxb.Dspl;
import com.google.dspl.model.Dataset;

/**
 * Converts a {@link Dataset} to a JAXB {@link Dspl}. Uses a {@link NamespaceMapping} to resolve
 * references to external datasets. Will throw an error during conversion if there is an external
 * reference that is not present in the mapping.
 *
 * @author Shardul Deo
 */
public class DatasetToDsplConverter {

  /**
   * Static utility method to convert a dataset that does not have any external references. For
   * proper conversion of datasets that have external references, construct a converter using
   * {@link #DatasetToDsplConverter(NamespaceMapping)} and use that.
   *
   * @param dataset The dataset that needs to be converted
   */
  public static Dspl convertDataset(Dataset dataset) {
    return new DatasetToDsplConversion(new NamespaceMapping(), dataset, null).convert();
  }

  /**
   * The same as {@link #convertDataset(Dataset)} but with a target namespace specified.
   *
   * @param targetNamespace The target namespace of the generated DSPL.
   */
  public static Dspl convertDataset(Dataset dataset, String targetNamespace) {
    return new DatasetToDsplConversion(new NamespaceMapping(), dataset, targetNamespace).convert();
  }

  private final NamespaceMapping namespaceMapping;

  /**
   * @param namespaceMapping Mapping between dataset namespaces and their ids. If the dataset being
   *        converted contains references to external datasets, this map must contain a mapping for
   *        them.
   */
  public DatasetToDsplConverter(NamespaceMapping namespaceMapping) {
    this.namespaceMapping = Preconditions.checkNotNull(namespaceMapping);
  }

  /**
   * @param dataset The dataset to be converted.
   * @param targetNamespace The target namespace of the generated DSPL. If null, generates the DSPL
   *        without a target namespace.
   */
  public Dspl convert(Dataset dataset, String targetNamespace) {
    return new DatasetToDsplConversion(namespaceMapping, dataset, targetNamespace).convert();
  }
}
